#-------------------------------------------------------------------------------
# Name:        ibrahim 
# Purpose:
#
# Author:      Sanchez
#
# Created:     28/06/2012
# Copyright:   (c) Sanchez 2012
# Licence:     <your licence>
#-------------------------------------------------------------------------------

import sys
from PyQt4 import QtGui, QtCore
from Ui_MainForm import Ui_MainWindow
import socket
import time
import struct
import numpy as np
import scipy as sc
import os

# creation de la classe  en derivant QThread
class AcquiNew(QtCore.QThread):
    "initialisation u thread affichage"
    def __init__(self):
        "initialisation du thread"
        QtCore.QThread.__init__(self)  # initialisation du thread
        w.index=0
        w.ListInfo.addItem("--- init trhead ----" )
        nomfic="newibrahim.dat"
        w.fd = open(nomfic, 'wb')
    def run(self):
        "programme principal du thread, excecution"
        w.ListInfo.addItem("--- debut trhead ----" )
        while (~w.finish):
            w.Status, w.indexStart, w.indexEnd=GetAdBufferStatus()
            #w.labelStatus.setText(str(w.Status)+" indexStart = "+str(w.indexStart) +" indexEnd = "+str(w.indexEnd))
            w.index=w.indexEnd-1000  # comme from GetAdBufferStatus
            if w.index>=0:
                GetScanRecord(w.index)
#            time.sleep(0.5)       # 0.4 a 5000         
        w.finish=True
        w.ListInfo.addItem("--- fin trhead ----" )
        w.fd.close() 


class MonAppli(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)

        # Configure l'interface utilisateur.
        self.setupUi(self)
        self.sock =0
        self.server_address = ('169.254.241.19',5025)
        self.level=1  # gain 1 +/- 10V
        self.finish=True
        self.Status, self.indexStart, self.indexEnd=0, 0, 0
        self.sCanCount, self.numChannel, self.scanIndex=0, 0, 0
  
#--------------------------------------------------------------------
# menus
#--------------------------------------------------------------------
  
#--------------------------------------------------------------------
# boutons
#--------------------------------------------------------------------
        self.connect(self.pushButtonConnect,QtCore.SIGNAL("clicked()"),On_pushButtonConnect)
        self.connect(self.pushButtonDeconnect,QtCore.SIGNAL("clicked()"),On_pushButtonDeconnect)
        self.connect(self.pushButtonSend,QtCore.SIGNAL("clicked()"),On_pushButtonSend)        
        self.connect(self.pushButtonStart,QtCore.SIGNAL("clicked()"),On_pushButtonStart)
        self.connect(self.pushButtonStop,QtCore.SIGNAL("clicked()"),On_pushButtonStop)        
  
  
#--------------------------------------------------------------------
# lineEdit
#--------------------------------------------------------------------
        self.connect(self.sCommand,QtCore.SIGNAL("returnPressed()"),On_sCommand)
#--------------------------------------------------------------------
# fonctions des menus 
#--------------------------------------------------------------------
#--------------------------------------------------------------------
# fonctions des boutons   
#--------------------------------------------------------------------


def ScpiQuery(sCommand):
    mess=sCommand+"\n"
    w.sock.sendall(mess)
    sResponse = w.sock.recv(1024)
    return repr(sResponse).strip("'").rstrip(r'\n')

def ScpiCommand(sCommand):
    mess=sCommand+"\n"
    err=w.sock.sendall(mess)
    return err
    

def GetAdBufferStatus():
    s=":AD:STAT?;:AD:STAT:SCAN?"
    sResponse=ScpiQuery(s)
    sResponse=sResponse.split(";")
    Status=int(sResponse[0])
    sResponse=sResponse[1]
    sResponse=sResponse.split(",")
    indexStart, indexEnd = int(sResponse[0]), int(sResponse[1])     
    return  Status, indexStart, indexEnd
    

    
def GetScanRecord(index):
 # recup donnees
    s=":AD:FETCH? "+str(index)+", 1000"
    #w.labelFetch.setText(s)
    err=ScpiCommand(s)
    amount_received = 0
    amount_expected = len(s)

    while amount_received < amount_expected:
        data = w.sock.recv(28) 
        amount_received += len(data)
    #---------------------------------------
    s=struct.unpack_from('2c',data)
    #---------------------------------------
    sizeHeader=int(s[1])  # en general 6 mais atention parfois 2
    # lecture taille du bloc de data suivant
    fmt=str(sizeHeader)+"c"    #formattage headertest.dat'
    s=struct.unpack_from(fmt,data[2:])
    L=len(s)
    lenRecord=0
    for i in range(L):
        lenRecord = pow(10,i)*int(s[L-i-1]) + lenRecord
    #--------------------------------------
    #lecture des 5 champ de 4 byte qui contituent le header
    if sizeHeader==6:
        fmt=">5l"
        header=struct.unpack_from(fmt,data[8:28])  # 2 + 6 du taille header
        header = np.array(header)
        header=sc.reshape(header,(1,5))
        header=header[0]
        # header(0) = index of first scan record in this block
        # header(1) = Number of scan records in this block
        # header(2) = Number of samples per enabled channel or scan record
        # header(3) = Time stamp of the first scan record in the block, in second
        # header(4) =  Time stamp of the first scan record in the block, in second
        sCanCount=header[0]
        #print sCanCount
    #--------------------------------------
    offset = 0
    RawRecord=[]
    total=0
    buff=str()
    while (offset < lenRecord-20):
        RawRecord = w.sock.recv(lenRecord - offset) 
        lenrecu=len(RawRecord)
        offset = offset + lenrecu
        buff=buff+RawRecord
    buff=buff[0:-1]     # enleve CR final
    w.fd.write(buff)    # write in the file only the data
    return 
 
#-----------------------------------------------------------------------------------------------------------------------    
def On_pushButtonConnect():
    print "pushButtonConnect"
    w.pushButtonConnect.setEnabled(False)
    w.pushButtonDeconnect.setEnabled(True)
    w.pushButtonSend.setEnabled(True)
    w.pushButtonStart.setEnabled(True)
    w.pushButtonStop.setEnabled(False)    
    # Create a TCP/IP socket
    w.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Bind the socket to the port
    w.server_address = ('169.254.241.19',5025)
    w.sock.connect(w.server_address)    
    w.ListInfo.addItem("connected...")
    w.ListInfo.scrollToBottom()
    return
  
def On_pushButtonDeconnect():
    print "pushButtonDeconnect"
    w.pushButtonConnect.setEnabled(True)
    w.pushButtonDeconnect.setEnabled(False)
    w.pushButtonStart.setEnabled(False)
    w.pushButtonSend.setEnabled(False)
    w.sock.close()
    w.ListInfo.addItem("Deconnected...")
    w.ListInfo.scrollToBottom()    
    return
    
def On_pushButtonSend():
    print "pushButtonSend"
    w.Command = str(w.sCommand.text()).rstrip()
    w.sResponse = ScpiQuery(w.Command)
    w.ListInfo.addItem(w.sResponse)
    w.ListInfo.scrollToBottom()
    return    


def On_pushButtonStart():
    print "pushButtonStart"
    w.pushButtonStart.setEnabled(False)
    w.pushButtonStop.setEnabled(True)  
    s="*RST"
    err=ScpiCommand(s)
    s=":AD:ENAB ON,(@1,2,3,4)"
    err=ScpiCommand(s)
    type="DC"
    s=":AD:COUP "+type+",(@1,2,3,4)"
    err=ScpiCommand(s)
    s=":AD:BUFF:MODE wrap"
    err=ScpiCommand(s)
    w.level=1
    s=":AD:GAIN "+str(w.level)+",(@1,2,3,4)"
    err=ScpiCommand(s)
    s=":AD:CLOCK:SOURCE INTERNAL"
    err=ScpiCommand(s)
    freq=10000
    s=":AD:CLOC:FREQ "+str(freq)
    err=ScpiCommand(s)
    s=":AD:TRIG IMM"
    err=ScpiCommand(s)
    s=":AD:ARM"
    err=ScpiCommand(s)
    s=":AD:INIT"
    err=ScpiCommand(s)
    w.ListInfo.addItem("debut acquisition...")
    w.ListInfo.scrollToBottom()  
    ThreadAcq.start()
    return
  
def On_pushButtonStop():
    print "pushButtonStop"
    w.pushButtonStart.setEnabled(True)
    w.pushButtonStop.setEnabled(False)    
    w.finish=True
    time.sleep(1)
    ThreadAcq.terminate()    
    s=":AD:ABORT"
    err=ScpiCommand(s)
    w.ListInfo.addItem("Arret acquisition...")
    w.ListInfo.scrollToBottom()      
    return
    
    
#--------------------------------------------------------------------
# fonctions des LineEdit    
#--------------------------------------------------------------------
def On_sCommand():
    " get w.sCommand.text()  faire la conversion vers int ou float"
    print "sCommand"
    pass
    return
    
    
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    w = MonAppli()
    ThreadAcq = AcquiNew()    # creation du thread
    w.show()
    w.pushButtonDeconnect.setEnabled(False)
    w.pushButtonSend.setEnabled(False)
    w.pushButtonStart.setEnabled(False)
    w.pushButtonStop.setEnabled(False)
    sys.exit(app.exec_())
